package com.dup.fastgpt.service;

import com.dup.fastgpt.dto.FastGptRequest;
import com.dup.fastgpt.dto.FastGptResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Service
@RequiredArgsConstructor
public class FastGptService {
    @Autowired
    private WebClient fastGptWebClient;
    @Autowired
    private RestTemplate restTemplate;

    @Value("${fastgpt.api.key}")
    private String apiKey;

    public Mono<FastGptResponse> sendMessage(FastGptRequest request) {
        request.setStream(false);
        request.setTemperature(0.7);

        WebClient.ResponseSpec mono=  fastGptWebClient.post()
                .uri("/v1/chat/completions")
                .bodyValue(request)
                .retrieve()
                .onStatus(
                        status -> status.is4xxClientError() || status.is5xxServerError(),
                        response -> response.bodyToMono(String.class)
                                .flatMap(error -> Mono.error(new RuntimeException("FastGPT API error: " + error))));

        return mono.bodyToMono(FastGptResponse.class);
    }

    /**
     * 流式响应支持
     */
    public Flux<String> streamChatCompletion(FastGptRequest request) {
        request.setStream(true);

        return fastGptWebClient.post()
                .uri("/v1/chat/completions")
                .bodyValue(request)
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class);
    }

    /**
     * 使用resttemplate调用fastGpt
     */
    public FastGptResponse sendMessageForRestTemplate(FastGptRequest request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        HttpEntity<FastGptRequest> entity = new HttpEntity<>(request, headers);

        try {
            ResponseEntity<FastGptResponse> response = restTemplate.exchange(
                    "https://cloud.fastgpt.cn/api/v1/chat/completions",
                    HttpMethod.POST,
                    entity,
                    FastGptResponse.class);

            return response.getBody();
        } catch (HttpClientErrorException e) {
            throw new RuntimeException("FastGPT API调用失败: " + e.getResponseBodyAsString(), e);
        } catch (RestClientException e) {
            throw new RuntimeException("调用FastGPT服务出错", e);
        }
    }
}
